package com.example.controll;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.exception.R;
import com.example.domain.Commodity;
import com.example.domain.Supplier;
import com.example.service.commodityServiceI;
import com.example.service.supServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/commodity")
public class CommodityController {

    @Autowired
    commodityServiceI commodityService;

    @Autowired
    supServiceI supplierService;

    @GetMapping
    private R getAll(){
        LambdaQueryWrapper<Commodity> lambdaQueryWrapper=new LambdaQueryWrapper<Commodity>();
        List<Commodity> commodityList=commodityService.list(lambdaQueryWrapper);
        return R.success(commodityList);
    }

    @GetMapping("/{id}")
    private R getById(@PathVariable Long id){
        Commodity commodity=commodityService.getById(id);
        return R.success(commodity);
    }

    @GetMapping("/wtihsupplier/{id}")
    private R getWithSupplier(@PathVariable Long id) {
        Commodity commodity = commodityService.getById(id);
        LambdaQueryWrapper<Supplier> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Supplier::getCommodityId, id);
        List<Supplier> list = supplierService.list(lambdaQueryWrapper);
        if(list.size()!=0){
            for(Supplier supplier:list){
                commodity.supplierList.add(supplier);
            }
        }
        return R.success(commodity);
    }

    @PostMapping
    private R addCommodity(@RequestBody Commodity commodity){
        commodityService.save(commodity);
        return R.success("添加成功");
    }

    @DeleteMapping("/{id}")
    private R deleteById(@PathVariable Long id){
        commodityService.removeById(id);
        return R.success("删除成功");
    }

}

